/* 3DGo Game
 * Copyright (C) 2008 Roman Hwang, Eugene Melnichek

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation - version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "Stone.h"
#include "d3dUtility.h"
#include "GameEngine.h"

using d3d::Vertex;

ID3DXMesh* Stone::m_spMesh = 0;
const float Stone::SPACING = 0.335f;
const float Stone::SCALING = 0.016f;



/////////////////////////////////////////////////////////////////////////////


Stone::Stone():m_color(WHITE), m_i(0), m_j(0)
{
	//Init();
}


/////////////////////////////////////////////////////////////////////////////


Stone::Stone(int _i, int _j, Color _color)
:m_color(_color), m_i(_i), m_j(_j), m_position()
{
	Init();

	CountMatrix();
}


/////////////////////////////////////////////////////////////////////////////


void Stone::Init()
{
	if (!m_spMesh)
	{
		HRESULT res = D3DXLoadMeshFromX("stone.x",
				      D3DXMESH_MANAGED,
					  pMyDevice,
					  NULL,
					  NULL,
					  NULL,
					  NULL,
					  &m_spMesh);

		if (FAILED(res))
		{
			throw std::exception("Mesh load failed" );
		}
	}
}


/////////////////////////////////////////////////////////////////////////////


void Stone::CountMatrix()
{
	// Set coordinates
	m_position.x = (m_j - 9) * Stone::SPACING;
	m_position.y = (9 - m_i) * Stone::SPACING;
	m_position.z = -0.05f;

	// Set material
	m_material = (m_color == BLACK) ? &d3d::BLACK_MTRL : &d3d::WHITE_MTRL;

	// World matrix computation
	D3DXMATRIX scale;
	D3DXMatrixScaling(&scale, Stone::SCALING, Stone::SCALING, Stone::SCALING);
	D3DXMATRIX pos;
	D3DXMatrixTranslation(&pos, m_position.x, m_position.y, m_position.z);
	m_world = scale * pos;
}


/////////////////////////////////////////////////////////////////////////////


void Stone::Render()
{
	pMyDevice->SetTransform( D3DTS_WORLD, &m_world );
	pMyDevice->SetMaterial(m_material);
	pMyDevice->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);
	m_spMesh->DrawSubset(0);
}


/////////////////////////////////////////////////////////////////////////////